var htmlorg = jQuery.fn.html;
jQuery.fn.html = function () {
	if (arguments.length == 2) {
		this.find(arguments[0]).html(arguments[1]);
		return this;
	}
	return htmlorg.apply(this, arguments);
}

var textorg = jQuery.fn.html;
jQuery.fn.text = function () {
	if (arguments.length == 2) {
		this.find(arguments[0]).text(arguments[1]);
		return this;
	}
	return textorg.apply(this, arguments);
}


GridMonitor = {
	statusGraph: null,
	statusData: [],
	pages: null,
	currentPage: function(){
		return jQuery('.page.selected');
	}
};

jQuery(document).ready(function() {
	GridMonitor.pages = jQuery('.page');
	GridMonitor.pages.each(function(page){
		jQuery(page).click(function(){
			changePage(page.id);
		});
	});
	// Load dashboard
	changePage('dashboard');
	update();
	// Create graphs
	setInterval(update, 10000);
});

function update(){
	jQuery.getJSON("/API.ashx/getnodes", function (data) { setData(data) });
	// jQuery.getJSON("/API.ashx/grids", function (data) { setGrids(data) });
}

function setData(data){
	setCounters(data);
	updateGraphs(data);
	updateNodeList(data);
	updateTimeline(data);
}

function setCounters(data){
	jQuery('.cgridnodes').text(data.length);
	jQuery('.cgridperformance').text(Math.round(parseFloat(Enumerable.From(data).Average("n => n.Processor"))*100) / 100);
	jQuery('.cgridcores').text(Enumerable.From(data).Sum("n => n.Cores"));
}

function two(a){
	if(a.toString().length != 2)
		return "0" + a;
	return a.toString();
}
function updateGraphs(data){
	if(!GridMonitor.statusGraph || data.length == 0)
		return;
	var time = new Date();
	var HH = two(time.getHours().toString());
	var mm = two(time.getMinutes().toString());
	var ss = two(time.getSeconds().toString());
	time = time.getFullYear() + "-" 
			+ two(time.getMonth())  + "-" 
			+ two(time.getDay())  + " " 
			+ HH + ":" + mm + ":" + ss;
	
	var point = { processor: Enumerable.From(data).Average("d => d.Processor"),
					memory: Enumerable.From(data).Average("d => d.Memory"),
					period: time
				};
	GridMonitor.statusData.push(point);
	if(GridMonitor.statusData.length > 50)
		GridMonitor.statusData = GridMonitor.statusData.slice(1);
	GridMonitor.statusGraph.setData(GridMonitor.statusData);
	GridMonitor.statusGraph
	
}
function nodesDetail(){

}

function performanceDetail(){

}
function coresDetail(){

}

function registerNewServer(name){
	jQuery.getJSON("/API.ashx/newnode?name=" + name, function(data){ setData(data)});
}

function changePage(page){
	GridMonitor.currentPage().toggleClass('selected');
	jQuery('#' + page + '.page').load('pages/' + page + '.html?'+new Date().getTime(), function(){
			onPageLoaded(page);
		}).toggleClass('selected');
}

function onPageLoaded(page){
	if(page == 'dashboard'){
		GridMonitor.statusGraph = Morris.Area({
			element: 'morris-area-chart',
			data: [],
			xkey: 'period',
			ykeys: ['processor', 'memory'],
			labels: ['Processor %', 'Memory %'],
			pointSize: 2,
			hideHover: 'auto',
			resize: true
		});
		update();
	}
}

function stopAllNodes() {
	jQuery.getJSON("/API.ashx/stopallnodes", function (data) { alert("All nodes stopped"); });
}

function updateTimeline(data) {
	var tl = jQuery('.timeline');
	if (tl.length == 0)
		return;
	var first = tl.find('li:first').clone();
	tl.find('li').remove();
	var flip = false;
	Enumerable.From(data).All(function (d) {
		tl.append(
				first.clone()
				.text(".timeline-title", d.MachineName + " (" + d.Cores + " <i class='fa fa-cogs fa-1x'></i>)")
				.text(".text-muted", d.LastUpdate)
				.html(".timeline-body", "Processor: " + d.Processor.toString().substring(0, 4) + " %<br/>"
				+ "Memory: " + d.Memory.toString().substring(0, 4) + " %<br/>"
				)
				.removeClass(flip ? "timeline-panel" : "timeline-inverted")
				.addClass(flip ? "timeline-inverted" : "timeline-panel")
			);
			flip = !flip;
		return true;
	});
}

function updateNodeList(data) {
	var nodelist = jQuery('.nodelist .nodes');
	if (nodelist.length == 0)
		return;
	var nodes = nodelist.find(".node");
	var first = jQuery(nodes.get(0));
	Enumerable.From(data).All(function (d) {
		nodelist.append(
				first.clone()
				.text(".cores", d.Cores)
				.text(".machinename", d.MachineName)
				.text(".memory", d.Memory)
				.text(".processor", d.Processor)

			);
		return true;
	});
	nodes.remove();
}

